package com.seeTools.next.service.sys.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seeTools.next.api.entity.sys.SysOss;
import com.seeTools.next.api.vo.SysOssBo;
import com.seeTools.next.api.vo.SysOssVo;
import com.seeTools.next.common.core.PageQuery;
import com.seeTools.next.common.core.ServiceException;
import com.seeTools.next.common.tools.FileUtils;
import com.seeTools.next.common.tools.SpringUtils;
import com.seeTools.next.common.tools.oss.core.OssClient;
import com.seeTools.next.common.tools.oss.entity.UploadResult;
import com.seeTools.next.common.tools.oss.enums.AccessPolicyType;
import com.seeTools.next.common.tools.oss.factory.OssFactory;
import com.seeTools.next.mapper.sys.SysOssMapper;
import com.seeTools.next.service.BaseServiceImpl;
import com.seeTools.next.service.sys.SysOssService;
import com.seeTools.next.util.PageQueryHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * OSS对象存储Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-05
 */
@Service
public class SysOssServiceImpl extends BaseServiceImpl<SysOssMapper, SysOss> implements SysOssService {


    @Resource
    private PageQueryHelper<SysOss> pageQueryHelper;

    /**
     * 分页查询
     *
     * @param pageQuery 分页数据
     * @return 对象
     */
    @Override
    public Page<SysOss> findList(PageQuery<SysOss> pageQuery) {
        QueryWrapper<SysOss> queryWrapper = getQueryWrapper(pageQuery.getParams());
        return dictionary(pageQueryHelper.pageInfo(this, pageQuery, queryWrapper));
    }


    /**
     * 查询数据
     *
     * @param model
     * @return
     */
    @Override
    public List<SysOss> selectDataList(SysOss model) {
        QueryWrapper<SysOss> queryWrapper = getQueryWrapper(model);
        return dictionary(list(queryWrapper));
    }

    /**
     * 图片上传
     *
     * @param file file
     * @return SysOssVo
     */
    @Override
    public SysOssVo upload(MultipartFile file) {
        String originalFileName = file.getOriginalFilename();
        if (StringUtils.isNotBlank(originalFileName)) {
            String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
            OssClient storage = OssFactory.instance();
            UploadResult uploadResult;
            try {
                uploadResult = storage.uploadSuffix(file.getBytes(), suffix, file.getContentType());
            } catch (IOException e) {
                throw new ServiceException(e.getMessage());
            }
            // 保存文件信息
            return buildResultEntity(originalFileName, suffix, storage.getConfigKey(), uploadResult);
        }
        return null;
    }

    private SysOssVo buildResultEntity(String originalFileName, String suffix, String configKey, UploadResult uploadResult) {
        SysOss oss = new SysOss();
        oss.setUrl(uploadResult.getUrl());
        oss.setFileSuffix(suffix);
        oss.setFileName(uploadResult.getFilename());
        oss.setOriginalName(originalFileName);
        oss.setService(configKey);
        save(oss);
        SysOssVo sysOssVo = BeanUtil.toBean(oss, SysOssVo.class);
        return this.matchingUrl(sysOssVo);
    }

    /**
     * 匹配Url
     *
     * @param oss OSS对象
     * @return oss 匹配Url的OSS对象
     */
    private SysOssVo matchingUrl(SysOssVo oss) {
        OssClient storage = OssFactory.instance(oss.getService());
        // 仅修改桶类型为 private 的URL，临时URL时长为120s
        if (AccessPolicyType.PRIVATE == storage.getAccessPolicy()) {
            oss.setUrl(storage.getPrivateUrl(oss.getFileName(), 120));
        }
        return oss;
    }


    @Override
    public void download(String ossId, HttpServletResponse response) throws IOException {
        SysOssVo sysOss = SpringUtils.getAopProxy(this).getById(ossId);
        if (ObjectUtil.isNull(sysOss)) {
            throw new ServiceException("文件数据不存在!");
        }
        FileUtils.setAttachmentResponseHeader(response, sysOss.getOriginalName());
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
        OssClient storage = OssFactory.instance(sysOss.getService());
        try (InputStream inputStream = storage.getObjectContent(sysOss.getUrl())) {
            int available = inputStream.available();
            IoUtil.copy(inputStream, response.getOutputStream(), available);
            response.setContentLength(available);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    public SysOssVo getById(String ossId) {
        SysOss sysOss = super.getById(ossId);
        SysOssVo sysOssVo = new SysOssVo();
        if (ObjectUtil.isNotEmpty(sysOss)) {
            BeanUtil.copyProperties(sysOss, sysOssVo);
        }
        return sysOssVo;
    }

    /**
     * 保存BO对象
     *
     * @param sysOssBo sysOssBo
     * @return
     */
    @Override
    public boolean saveBo(SysOssBo sysOssBo) {
        SysOss sysOss = new SysOss();
        BeanUtil.copyProperties(sysOssBo, sysOss);
        return super.save(sysOss);
    }


    /**
     * 获取查询条件
     *
     * @param model
     * @return
     */
    public QueryWrapper<SysOss> getQueryWrapper(SysOss model) {
        QueryWrapper<SysOss> queryWrapper = new QueryWrapper<>();
        LambdaQueryWrapper<SysOss> lambdaQueryWrapper = queryWrapper.lambda();
        if (ObjectUtil.isNotEmpty(model)) {
            // 文件名称
            if (StrUtil.isNotBlank(model.getFileName())) {
                lambdaQueryWrapper.eq(SysOss::getFileName, model.getFileName());
            }
            // 原名
            if (StrUtil.isNotBlank(model.getOriginalName())) {
                lambdaQueryWrapper.eq(SysOss::getOriginalName, model.getOriginalName());
            }
            // 文件后缀
            if (StrUtil.isNotBlank(model.getFileSuffix())) {
                lambdaQueryWrapper.eq(SysOss::getFileSuffix, model.getFileSuffix());
            }
            // 创建时间
         /*   if (ObjectUtil.isNotEmpty(model.getBeginTime()) && ObjectUtil.isNotEmpty(model.getEndTime())) {
                lambdaQueryWrapper.between(SysOss::getCreateDate, model.getBeginTime(), model.getEndTime());
            }*/
            //上传人
            if (StrUtil.isNotBlank(model.getCreateBy())) {
                lambdaQueryWrapper.eq(SysOss::getCreateBy, model.getCreateBy());
            }
            // 服务商
            if (StrUtil.isNotBlank(model.getService())) {
                lambdaQueryWrapper.eq(SysOss::getService, model.getService());
            }

        }
        return queryWrapper;
    }


    /**
     * 翻译数据
     *
     * @param page
     * @return
     */
    public Page<SysOss> dictionary(Page<SysOss> page) {
        if (ObjectUtil.isNotEmpty(page)) {
            List<SysOss> list = page.getRecords();
            dictionary(list);
        }
        return page;
    }

    /**
     * 翻译
     *
     * @param list
     * @return
     */
    public List<SysOss> dictionary(List<SysOss> list) {
        if (CollUtil.isNotEmpty(list)) {
            list.forEach(item -> {
            });
        }
        return list;
    }

}

